package com.test.chatdemo.filter;

import com.alibaba.fastjson.JSONObject;
import com.test.chatdemo.pojo.Result;
import com.test.chatdemo.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*", asyncSupported = true)
public class UserFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(UserFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取url
        String url = request.getRequestURL().toString();
        log.info("请求的url:{}", url);

        // 判断请求是否放行
        if (url.contains("login") || url.contains("register") || url.contains("captcha")) {
            log.info("放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 新增：放行静态资源
        if (url.endsWith(".html") || url.endsWith(".css") || url.endsWith(".js") ||
                url.endsWith(".ico") || url.endsWith(".png") || url.endsWith(".jpg") ||
                url.endsWith(".jpeg") || url.endsWith(".gif")) {
            log.info("静态资源，放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 新增：放行根路径
        if (url.equals("http://localhost:8080/") || url.endsWith("/")) {
            log.info("根路径，放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取请求头令牌
        String jwt = request.getHeader("token");

        // 判断令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            log.info("token为空，返回未登录的信息");
            Result error = Result.error("无法登录");

            String noLogin = JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return;
        }

        // 解析token
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回");

            Result error = Result.error("无法登录");
            String noLogin = JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return;
        }

        // 放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}